#include "comm.hpp"

// 创建共享内存
int main()
{
    // 1.创建key
    key_t key = ftok(PROC_PATH, PROJ_ID);
    assert(key != -1);
    std::cout << "--ftok success--" << std::endl;
    sleep(2);

    // 2.创建共享内存
    int shmId = shmget(key, SHM_SIZE, IPC_CREAT | IPC_EXCL | 0666); // 不存在就创建，存在就报错
    assert(shmId != -1);
    std::cout << "--shmget success--" << std::endl;
    sleep(2);

    // 3.进程attach共享内存
    char *pshm = (char *)shmat(shmId, nullptr, 0);
    assert(pshm != (char *)-1);
    std::cout << "--shmat success--" << std::endl;
    sleep(5);

    // 4.通信-服务端读取
    while (true)
    {
        std::cout << pshm << std::endl;
        if (strcmp(pshm, "quit") == 0)
        {
            std::cout << "--server quit!!--" << std::endl;
            break;
        }
        sleep(1);
    }

    // 5.进程detach共享内存
    int n = shmdt(pshm);
    assert(n != -1);
    std::cout << "--shmdt success--" << std::endl;
    sleep(2);

    // 6.释放共享内存
    shmctl(shmId, IPC_RMID, nullptr);
    std::cout << "--shmctl success--" << std::endl;
    sleep(2);

    return 0;
}